package hars

import (
	"encoding/json"
	"ga-ga/catch"
	"ga-ga/models"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	name := c.PostForm("name")
	title := c.PostForm("title")
	data := models.Post{
		Name:  name,
		Title: title,
	}
	if name == "" || title == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不为空",
			"data": nil,
		})
		return
	}
	models.DB.Create(&data)
	redis_key := "article_" + strconv.Itoa(int(data.ID))
	var article models.Post
	models.DB.Where("id = ?", data.ID).First(&article)
	jsonData, _ := json.Marshal(article)
	catch.Rdb.Set(catch.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
		"data": article,
	})
	return
}
func Del(c *gin.Context) {

	id := c.Query("id")
	models.DB.Where("id = ?", id).Delete(&models.Post{})

	redis_key := "article_" + id
	catch.Rdb.Del(catch.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return

}

//	func List(c *gin.Context) {
//		var article []models.Post
//		//redis_key := "redis_key"
//		//catchcount, _ := catch.Rdb.Get(catch.Ctx, redis_key).Result()
//		//if catchcount == "" {
//		//	models.DB.Find(&models.Post{})
//		//	jsondata, _ := json.Marshal(&article)
//		//	catch.Rdb.Set(catch.Ctx, redis_key, jsondata, time.Hour*2)
//		//} else {
//		//	json.Unmarshal([]byte(catchcount), &article)
//		//}
//		models.DB.Find(&models.Post{})
//		c.JSON(200, gin.H{
//			"code": 200,
//			"msg":  "查询成功",
//			"data": article,
//		})
//		return
//
// }
func List(c *gin.Context) {
	var articles []models.Post

	//设置redis的key
	redis_key := "list"
	cacheData, _ := catch.Rdb.Get(catch.Ctx, redis_key).Result()

	if cacheData == "" {
		models.DB.Find(&articles)
		jsonData, _ := json.Marshal(articles)
		catch.Rdb.Set(catch.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &articles)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"data": articles,
		"msg":  "success",
	})
	return
}
